package hhm.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

public class ListUtils {

	public static int findValue(List<?> list, String fieldName, String value) {

		for (int i = 0; i < list.size(); i++) {
			Object o = list.get(i);
			try {
				Method method = o.getClass().getMethod("get" + change(fieldName));

				Object val = method.invoke(o);

				if (val.toString().equals(value)) {

					return i;

				}

			} catch (SecurityException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException
					| InvocationTargetException e) {
				e.printStackTrace();
			}
		}

		return -1;
	}

	public static <T> List<T> getFiledList(List<?> list, Class<T> type) {
		if (CollectionUtils.isEmpty(list))
			return null;
		List<T> filedList = new ArrayList<>();
		try {
			for (Object obj : list) {
				Class<? extends Object> clazz = obj.getClass();// 获取集合中的对象类型
				Field[] fds = clazz.getDeclaredFields();// 获取他的字段数组
				for (Field field : fds) {// 遍历该数组
					String fdname = field.getName();// 得到字段名，

					Method method = clazz.getMethod("get" + change(fdname));// 根据字段名找到对应的get方法，null表示无参数
					if (null != method && type.getSimpleName().equals(change(fdname))) {
						Object val = method.invoke(obj);
						filedList.add(type.cast(val));
					}

				}
			}

		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return filedList;
	}

	/**
	 * @param src
	 *            源字符串
	 * @return 字符串，将src的第一个字母转换为大写，src为空时返回null
	 */
	public static String change(String src) {
		if (src != null) {
			StringBuffer sb = new StringBuffer(src);
			sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
			return sb.toString();
		} else {
			return null;
		}
	}

}
